﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace WPFTemplateLib.WpfHelpers
{
    /// <summary>
    /// DependencyObject 的扩展类
    /// </summary>
    public static class DependencyObjectExtension
    {
        /// <summary>
        /// WPF中查找元素的父元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The i_dp.</param>
        /// <returns>T.</returns>
        public static T FindParent<T>(this DependencyObject obj) where T : DependencyObject
        {
            DependencyObject dependencyObject = (DependencyObject)VisualTreeHelper.GetParent(obj);
            if (dependencyObject != null)
            {
                if (dependencyObject is T t)
                {
                    return t;
                }
                else
                {
                    dependencyObject = FindParent<T>(dependencyObject);
                    if (dependencyObject is T t1)
                    {
                        return t1;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// WPF查找指定类型子元素
        /// </summary>
        /// <typeparam name="T">The type of the child item.</typeparam>
        /// <param name="obj">The object.</param>
        /// <returns>childItem.</returns>
        public static T FindVisualChild<T>(this DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child is T t)
                    return t;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

        /// <summary>
        /// WPF查找所有指定类型子元素.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="depObj">The dep object.</param>
        /// <returns>IEnumerable&lt;T&gt;.</returns>
        public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child is T t)
                    {
                        yield return t;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
    }
}
